package utils;

import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Vector;

public class DBManager {

	static private DBManager instance;

	static private int clients;
	private DBConnectionPool pools;

	// get a instance of DBManager
	public static synchronized  DBManager getInstance() {
		if (instance == null) {
			instance = new DBManager();
		}
		clients++;
		return instance;
	}

	/**
	 * private constructor
	 */
	private DBManager() {
		init();
	}

	public void freeConnection(Connection conn) {
		pools.freeConnection(conn);
	}

	// Get a connection from connection pool
	public Connection getConnection() {
		Connection conn = pools.getConnection();
		if (pools != null) {
			return conn;
		} else {
			return conn;
		}
	}

	/**
	 * if not clients using then release Connection Pool
	 */
	public synchronized void release() {
		if (--clients != 0) {
			return;
		}
		pools.release();
	}

	private void init() {
		pools = new DBConnectionPool();
	}
	
	
	public ResultSet executeQuery(String sql){
		Connection conn = this.getConnection();
		ResultSet rs = null;
		
		try {
			Statement stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
		    freeConnection(conn);
		    
		}
		
		return rs;	
		
	}
	
	public int excuteUpdate(String sql){
		Connection con = this.getConnection();
		int result = 0;
		try{
			Statement stmt = con.createStatement();
			result = stmt.executeUpdate(sql);
		}catch (SQLException e){
			e.printStackTrace();
		}finally{
			freeConnection(con);
		}
		
		return result;
		
	}
	
	
	
	

}
